<!--
* description: 新增编辑-电池退役维护
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      width="70%"
      @close="closeEdit"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :o-fields="comp.oFields"
            :options="comp.options"
            :custom-obj="comp.customObj"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 8"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :data-to-object="comp.dataToObj"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
          >{{ comp.text }}</el-button
        >
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from "@/components/wms/mixins/formMixins";
import api from "@/api/se/apiBaseData";
import request from "@/utils/request";

export default {
  components: {
    dialogHeader: () => import("@/components/dialogHeader"),
    mixButton: () => import("@/components/basicComponent/mixButton"),
  },

  // 组件混入对象
  mixins: [formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },

  data() {
    const viewPageCode = "bigAreaInfo-edit";
    return {
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          icon: "iconfont  icon-preservation",
          clickEvent: () => this.saveSubmit(0),
          text: this.$t("sys.button.save") /* 保存*/,
          position: "right",
        },
        {
          compKey: "btnKey2",
          type: "",
          size: "small",
          icon: "iconfont  icon-preservation",
          clickEvent: () => this.saveSubmit(1),
          text: this.$t("sys.button.submitSave"), //提交
        },
        {
          compKey: "btnKey3",
          type: "",
          size: "small",
          icon: "iconfont  icon-cancel",
          clickEvent: () => this.close(),
          text: this.$t("sys.button.cancel"), // 取消
        },
      ],

      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: "compKey1",
          labelName: "门店编码：",
          codeField: "dlrCode",
          disabled: true,
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isMul: false,
          isMust: true,
        },
        {
          compKey: "compKey2",
          labelName: "门店名称：",
          codeField: "dlrName",
          disabled: true,
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isMul: false,
          isMust: true,
        },
        {
          compKey: "compKey3",
          labelName: "VIN：",
          codeField: "vin",
          disabled: true,
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isMul: false,
          isMust: true,
        },
        {
          compKey: "compKey4",
          labelName: "派工单号：",
          codeField: "repairOrderCode",
          isRequire: true,
          disabled: false,
          component: () => import("@/components/se/dispatchOrderNo"),
          type: "inputText",
          isMul: false,
          isMust: true,
        },
        {
          compKey: "compKey5",
          labelName: "电池编号",
          codeField: "batteryCode",
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          // disabled: true,
          isRequire: true,
          isMust: true,
        },
        {
          compKey: "compKey6",
          labelName: "电池类型",
          codeField: "batteryType",
          textField: "batteryTypeName",
          customObj: {
            api: api.queryBatteryType,
            defOptionFields: ["batteryTypeCode", "batteryTypeName"],
          },
          component: () => import("@/components/org/commonSelect"),
          type: "dropdownList",
          isRequire: true,
          isMust: true,
        },
        {
          compKey: "compKey7",
          labelName: "退役去向厂商名称：",
          codeField: "whereaboutsName",
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isRequire: true,
          isMust: true,
        },
        {
          compKey: "compKey8",
          labelName: "退役去向厂商统一社会信用代码：",
          codeField: "whereaboutsCode",
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isRequire: true,
          isMust: true,
        },
        {
          compKey: "compKey9",
          labelName: "退役企业类型：",
          codeField: "factoryType",
          textField: "factoryTypeName",
          customObj: {
            api: api.queryFactoryType,
            defOptionFields: ["factoryTypeCode", "factoryTypeName"],
          },
          component: () => import("@/components/org/commonSelect"),
          isRequire: true,
          isMust: true,
        },
        {
          compKey: "compKey10",
          labelName: "退役厂商名称：",
          codeField: "retireUnitName",
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isRequire: true,
          isMust: true,
        },
        {
          compKey: "compKey11",
          labelName: "退役厂商统一社会信用代码：",
          codeField: "retireUnitCode",
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isRequire: true,
          isMust: true,
        },
        {
          compKey: "compKey12",
          labelName: "电池质量（千克）：",
          codeField: "batteryWeight",
          validrule: {
            isformat: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/,
            resectMessage: {
              isformat: "电池质量（千克）只能是数字!",
            },
          },
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isRequire: true,
          isMust: true,
        },
        {
          compKey: "compKey13",
          labelName: "退役产品类型：",
          codeField: "batterySpeciesCode",
          // textField: "batterySpecies",
          customObj: {
            api: api.retiredProductType,
            defOptionFields: ["batterySpeciesCode","batterySpeciesName"],
          },
          component: () => import("@/components/org/commonSelect"),
          isRequire: true,
          isMust: true,
        },
        {
          compKey: "compKey14",
          labelName: "退役日期：",
          codeField: "retireDate",
          component: () => import("@/components/org/datePicker/datePicker"),
          type: "datePicker",
          type: "inputText",
          isMul: false,
          isRequire: true,
          isMust: true,
        },
      ],

      // 标题
      textMap: {
        edit: "电池退役维护修改",
        add: "电池退役维护新增",
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: {
        dlrCode: "",
        dlrName: "",
        vin: "",
        batteryCode: "",
        batteryType: "",
        whereaboutsName: "",
        whereaboutsCode: "",
        factoryType: "",
        retireUnitName: "",
        retireUnitCode: "",
        batteryWeight: "",
        repairOrderCode: "",
        updateControlId: "",
        batteryRetireId: "",
        batterySpeciesCode: "", //退役产品类型
        batterySpeciesName: "", //退役产品类型
        retireDate: "", //退役日期
      },
    };
  },
  watch: {
    "formField.repairOrderCode": {
      handler(val, old) {
        if (val != "" && val != old) {
          if (this.popupsState != "edit") {
            // debugger
            this.getInfoDispatchOrderNo(val);
          }
        }
      },
      deep: true,
    },
  },
  methods: {
    // 派工单选择
    getInfoDispatchOrderNo(val) {
      request({
        url: api.findAddInfo.APIUrl,
        method: "post",
        data: { repairOrderCode: val },
      }).then((res) => {
        if (res.result == "1") {
          this.formField = Object.assign(this.formField, res.rows[0]);
        }
      });
    },
    // 关闭弹窗
    // handleClose(done) {
    //   this.$confirm('还未保存，确认关闭窗口？')
    //     .then(_ => {
    //       this.$emit('update:curPopupsVisible', false)
    //       done()
    //     })
    //     .catch(_ => {})
    // },
    onCreated() {
      if (this.curPopupsVisible) {
        if (this.popupsState === "edit") {
          this.tableComponents[3].disabled = true;
        }
      }
    },
    closeEdit() {
      this.$emit("close", false);
    },
    // 新增/编辑保存按钮
    saveSubmit(type) {
      const that = this;
      this.$utils.validataMoth(this, "validpopup");
      if (!this.valid) {
        return;
      } else {
        if (that.popupsState === "edit") {
          that.editSave(type);
        } else {
          that.addSave(type);
        }
      }
      // this.closeEdit();
    },

    // 编辑保存
    editSave(type) {
      const that = this;
      that.formField.isCommit = type;
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: api.updateBatteryRetired,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField,
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === "1") {
          this.$message({
            message: this.$t("sys.tips.esTip5") /* 保存成功*/,
            type: "success",
            duration: 1000,
          });
          this.curPopupsVisible = false;
          this.$nextTick(() => {
            this.$parent.queryTable(1);
          });
        } else {
          // 保存失败
          this.$message({
            message: "保存失败:" + response.msg,
            type: "warn",
            uration: 1000,
          });
        }
        // this.curPopupsVisible = false;
      });
    },

    // 新增保存
    addSave(type) {
      const that = this;
      that.formField.isCommit = type;
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: api.insertBatteryRetired,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField,
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === "1") {
          this.$message({
            message: response.msg,
            type: "success",
            duration: 1000,
          });
          this.curPopupsVisible = false;
          this.$nextTick(() => {
            this.$parent.queryTable(1);
          });
        } else {
          // 保存失败
          this.$message({
            message: response.msg,
            type: "warn",
            uration: 1000,
          });
        }
        // this.curPopupsVisible = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.promptSpan {
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
</style>

